Ext.define('RDB.controller.DisplayCustomersController', {
	extend: 'Ext.app.Controller',

	init: function() {
		this.control({
			'displaycustomers': {
				show: this.onGridShow
			},
			'displaycustomers button[name=addcustomer]': {
				click: this.onAddCustomer
			},
			'displaycustomers button[name=removecustomer]': {
				click: this.onRemoveCustomer
			},
			'displaycustomers button[name=download_xls]': {
				click: this.onDownloadXLS
			},
			'displaycustomers grid': {
				edit: this.onGridEdit
			}
		});
	},

	onGridShow: function(win, eOpts) {
		var store = win.down('grid').getStore();
		store.load();
	},

	onAddCustomer: function(btn, eOpts) {
		var win = btn.up('window'),
			grid = win.down('grid'),
			store = grid.getStore(),
			plugin = grid.getPlugin();
		store.insert(0, Ext.create('RDB.models.CustomersModel'));
		plugin.startEdit(0, 0);
		console.log(arguments);
	},

	onRemoveCustomer: function(btn, eOpts) {
		console.log(arguments);
		var win = btn.up('window'),
			grid = win.down('grid'),
			store = grid.getStore(),
			selection = grid.getView().getSelectionModel().getSelection()[0];

		Ext.Msg.show({
        	title:'Delete Record?',
           	msg: 'You are deleting a record permanently, this cannot be undone. Proceed?',
           	buttons: Ext.Msg.YESNO,
           	icon: Ext.Msg.QUESTION,
           	fn: function(btn){
           		if (btn === 'yes'){
                	if (selection) {
						store.remove(selection);
					}
            	}
           }
      	});
	},

	onDownloadXLS: function(btn, eOpts) {
		Ext.Ajax.request({
			url: '/bin/web_api/reports.py/get_customers_xls',
			success: function(response, opts){
				window.location = response.responseText;
			},
			failure: function(response, opts){
				console.log(arguments);
			}
		});
	},

	onGridEdit: function(grid, ctx, eOpts) {
		ctx.grid.getStore().load();
	}
});
